package com.raycloud.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.raycloud.constants.SystemConstant;
import com.raycloud.dao.EndProjectDAO;
import com.raycloud.dao.FrontProjectDAO;
import com.raycloud.dao.VersionDAO;
import com.raycloud.pojo.EndProject;
import com.raycloud.pojo.Version;
import com.raycloud.query.EndProjectQuery;
import com.raycloud.query.VersionQuery;
import com.raycloud.util.CmdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Created by donar on 17/4/19.
 */
@Controller
@RequestMapping("/end")
public class EndProjectController {
    @Autowired
    FrontProjectDAO frontProjectDAO;
    @Autowired
    EndProjectDAO endProjectDAO;
    @Autowired
    VersionDAO versionDAO;
    @RequestMapping(value = "init")
    @ResponseBody
    public Response initProject(@ModelAttribute EndProject project)  {
        if(StringUtils.isEmpty(project.getProjectName())) return Response.error("项目名不能为空");
        if(endProjectDAO.getEndProjectByKey(project.getProjectName())!=null) return Response.error("项目名已存在");
        if(StringUtils.isEmpty(project.getTomcatPort()))return Response.error("tomcat端口不能为空");
        if(StringUtils.isEmpty(project.getDubboPort())) return Response.error("dubbo端口不能为空");
        if(StringUtils.isEmpty(project.getOwner())) return Response.error("责任人不能为空");
        if(StringUtils.isEmpty(project.getGitPath())) return Response.error("git路径不能为空");
        if(StringUtils.isEmpty(project.getBranch())) return Response.error("请选择分支");
        if(StringUtils.isEmpty(project.getProfile())) return Response.error("请选择编译参数");
        if(StringUtils.isEmpty(project.getModuleName())) return Response.error("请选择模块名称");
        if(StringUtils.isEmpty(project.getFinalName())) return Response.error("请填写finalName");
        try{
            checkPortExist(project.getTomcatPort(),project.getDubboPort(),project.getTomcatPort()-1);
        }catch (Exception e){
            return Response.error(e.getMessage());
        }
        String cmd = "sh "+SystemConstant.ROOT_PATH+"/newproject.sh {0} {1} {2} {3} {4} {5} {6} {7}";// project tomcat dubbo git
        String result = CmdUtil.exec(MessageFormat.format(cmd,project.getProjectName(),project.getTomcatPort()+"",project.getDubboPort()+"",project.getGitPath(),project.getBranch(),project.getProfile(),project.getModuleName(),project.getFinalName()));
        endProjectDAO.addEndProject(project);
        return Response.success(result);
    }

    private void checkPortExist(int tomcatPort, int dubboPort, int shutdownPort) throws Exception {
        Set<Integer> ports = new HashSet<Integer>();

        for (EndProject project :endProjectDAO.getEndProjectList(new EndProjectQuery())){
            ports.add(project.getTomcatPort());
            ports.add(project.getTomcatPort()-1);
            ports.add(project.getDubboPort());
        }
        if(ports.contains(tomcatPort)) throw new Exception("tomcat port has already been used");
        if(ports.contains(shutdownPort)) throw new Exception("shutdownport = tomcatport -1  which  has already been used");
        if(ports.contains(dubboPort)) throw new Exception("dubbo port has already been used");
    }

    @RequestMapping(value = "projectList")
    @ResponseBody
    public Response getProjectList()  {
        return Response.success(endProjectDAO.getEndProjectList(new EndProjectQuery()));
    }

    @RequestMapping(value = "removeProject")
    @ResponseBody
    public Response deleteProject(String projectName)  {
        List<Version>  versions = versionDAO.getVersionList(new VersionQuery());
        for (Version v:versions){
            JSONArray array = JSON.parseArray(v.getEndProjectsInfo());
            for (Object o:array){
                JSONObject obj=(JSONObject) o;
                if(projectName.equals(obj.getString("project")))return Response.error("版本号"+v.getVersionId()+"正关联此项目。请先删除相关版本再删除该项目");
            }
        }
        String result1 = CmdUtil.exec("sh "+ SystemConstant.ROOT_PATH+"/"+projectName+"/publish.sh stop");
        String result = CmdUtil.exec("sh "+SystemConstant.ROOT_PATH+"/deleteProject.sh "+projectName);
        endProjectDAO.deleteByKey(projectName);
        return Response.success("删除成功");
    }

    @RequestMapping(value = "publish")
    @ResponseBody
    public Response restart(String projectName)  {
        String result = CmdUtil.exec("sh "+SystemConstant.ROOT_PATH+"/"+projectName+"/publish.sh");
        String monitor = CmdUtil.exec("cp /data/project/index_monitor.sh "+SystemConstant.ROOT_PATH+"/"+projectName+"/code/");
        return Response.success(result);
    }
    @RequestMapping(value = "restart")
    @ResponseBody
    public Response deploy(String projectName)  {
        String result = CmdUtil.exec("sh "+SystemConstant.ROOT_PATH+"/"+projectName+"/publish.sh restart");
        return Response.success("重启成功");
    }
    @RequestMapping(value = "shutdown")
    @ResponseBody
    public Response shutdown(String projectName)  {
        String result = CmdUtil.exec("sh "+ SystemConstant.ROOT_PATH+"/"+projectName+"/publish.sh stop");
        return Response.success("关闭成功");
    }
}
